const koa = require('koa');
const router = require('./routes/router');
const bodyParser = require('koa-bodyparser');
const cors = require('koa2-cors');
const config = require('./config/baseConfig');
const _ = require('underscore');
const JWT = require('koa-jwt');
const jwtKoa = require('jsonwebtoken')
const app = new koa();
const { getToken } = require('./api/index')
const server = require('http').createServer(app.callback());
const io = require('socket.io')(server, { cors: true })
app.use(cors());
let isRefresh = false;
app.use(async (ctx, next) => {
  return next().catch(err => {
    if (err.status === 401) {
      // 自定义返回结果
      ctx.status = 401;
      console.log(err.name);
      ctx.body = {
        code: 401,
        msg: err.message
      };
    } else {
      throw err;
    }
  });
});
/* const jwt = JWT({
  secret: config.secret, algorithms: ["HS256"]
}).unless({
  path: [
    /^\/login/, // 登陆接口
    /^\/register/ // 注册
  ]
}) */
app.use(bodyParser());
/* app.use(jwt); */

app.use(async (ctx, next) => {
  // 获取请求头中的两个token  
  const accessToken = ctx.request.header.authorization;

  if (ctx.path == '/login' || ctx.path == '/register'|| ctx.path == '/refresh') {
    console.log(ctx.path);
     await next()
     return
  }
  // 验证第一个token
  if (!ctx.request.header.refreshtoken) {
    try {
      console.log(777777);
      const decoded1 = jwtKoa.verify(accessToken.slice(7), config.secret);
      if (decoded1) {
        console.log(decoded1);
      } else {
        console.log('baoc');
      }
    } catch (error) {
        ctx.status = 402
        ctx.body = {
          code: 402,
          message: 'accessToken失效',
          config: {
            url: ctx.path,
            method: 'POST',
            data:ctx.request.body
          }
      }
      
    }
  }
    
  
  // 执行其他处理逻辑...  
  
  await next(); // 继续处理请求  

});
router.post('/refresh', async (ctx, next) => {
  const refreshToken = ctx.request.header.refreshtoken;
 console.log(refreshToken);
  try {
    const decoded2 = jwtKoa.verify(refreshToken.slice(7), config.secret);
    if (decoded2) {
      console.log('第二个token验证成功：', decoded2);
      const accessToken = getToken({ id: decoded2.id, username: decoded2.username }, true)
      const RefreshToken = getToken({ id: decoded2.id, username: decoded2.username }, false)
      console.log(accessToken,RefreshToken);
      ctx.status = 200
      ctx.body = {
        code: 206,
        data: {
          accessToken: `Bearer ${accessToken}`,
          refreshToken: `Bearer ${RefreshToken}`,
        }
      }
      isRefresh = false
    }
  } catch (error) {
    console.log('errorttt', error);
    ctx.status = 401
    ctx.body = {
      code: 401,
      message: 'refreshToken失效'
    }
  }
})
app.use(router.routes()).use(router.allowedMethods())
let socketList = new Map()


io.on('connection', socket => {
  socket.on('login', (data) => {
    if (!socketList.has(data.id)) {
      socketList.set(data.id, socket)
    }

    console.log('login', data, socketList.size);

  })
  socket.on("receive", (info) => {
    for (const item of socketList) {
      if (item[0] === info.receiverId) {
        item[1].emit('message', info)
        break;
      }
    }

    // socket.on方法,服务端监听客户端emit的事件，事件名字为 "receive", 并且接收客户端发送过来的信息
  })
  socket.on('disconnect', () => {
    console.log('disconnect');
  })

})

server.listen(3000, () => {
  console.log('服务端已启动在http://localhost:3000');
})

